<template>
  <div class="body">
    <div class="table-wrap">
      <div class="search_header">
        <span>
          <el-button
            icon="el-icon-plus"
            @click="
              dialogVisible = true
              headerTitle = '新增用户'
            "
            v-has="'userManagement:add'"
            >新增用户</el-button
          >
        </span>
        <div class="search_header_right">
          <el-input
            placeholder="请输入真实姓名"
            v-model="parameter.userName"
            @keyup.enter.native="search"
            @clear="search"
            clearable
          >
            <span
              @click="search"
              slot="suffix"
              style="display: inline-block"
            >
              <Icon
                title="搜索"
                name="sousuo"
                color="#A7ADB5"
                font-size="20"
              />
            </span>
          </el-input>
          <el-select
            placeholder="用户角色"
            v-model="parameter.roleId"
            clearable
            @change="search"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.pkid"
              :label="item.roleName"
              :value="item.pkid"
            >
            </el-option>
          </el-select>
          <el-cascader
            placeholder="选择部门"
            clearable
            @change="search"
            v-model="parameter.deptId"
            :options="deptTree"
            :props="{
              value: 'pkid',
              label: 'deptName',
              children: 'childTree',
              checkStrictly: true
            }"
          />
          <el-select
            placeholder="用户状态"
            v-model="parameter.userState"
            clearable
            @change="search"
          >
            <el-option
              v-for="item in stateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <el-table
        :data="userList"
        :header-cell-style="{
          background: '#F2F6FB ',
          color: ' #6B767D'
        }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          label="用户名"
          prop="loginName"
          show-overflow-tooltip
        />
        <el-table-column
          label="真实姓名"
          prop="userName"
          show-overflow-tooltip
        />
        <el-table-column
          label="用户角色"
          prop="roleName"
          show-overflow-tooltip
        />
        <el-table-column
          label="所属单位"
          prop="deptName"
          show-overflow-tooltip
        />
        <el-table-column label="用户状态">
          <template v-slot="scope">
            {{
              scope.row.userState === 1 ? '启用' : '禁用'
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="联系电话"
          prop="userPhone"
          show-overflow-tooltip
        />
        <el-table-column
          label="电子邮箱"
          prop="userEmail"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
          show-overflow-tooltip
        />
        <el-table-column
          label="修改时间"
          prop="updateTime"
          show-overflow-tooltip
        />
        <el-table-column
          label="备注"
          prop="remark"
          show-overflow-tooltip
        />
        <el-table-column
          label="操作"
          show-overflow-tooltip
          width="140"
        >
          <template v-slot="scope">
            <el-button
              v-has="'userManagement:edit'"
              @click="updateUser(scope.row)"
              type="text"
              style="color: #00baff; font-weight: 400"
              >编辑</el-button
            >
            <el-button
              v-has="'userManagement:delete'"
              @click="deleteUser(scope.row)"
              type="text"
              style="color: #ff5b5b; font-weight: 400"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-pagination" v-if="total">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="parameter.pageSize"
          @current-change="pageChange"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      @close="onClose"
      :title="headerTitle"
      width="600px"
      top="40px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        label-width="100px"
        :model="addUser"
        :rules="rules"
        v-if="dialogVisible"
        ref="ruleForm"
      >
        <el-form-item label="登录名" prop="loginname">
          <el-input v-model="addUser.loginname" clearable />
        </el-form-item>
        <el-form-item label="真实姓名" prop="userName">
          <el-input v-model="addUser.userName" clearable />
        </el-form-item>
        <el-form-item
          label="登录密码"
          prop="loginpassword"
          v-if="!pkid"
        >
          <el-input
            v-model="addUser.loginpassword"
            clearable
            show-password
          />
        </el-form-item>
        <!--          <el-form-item label='原始密码' prop='oldloginpassword' v-if="pkid"><el-input v-model='addUser.oldloginpassword' clearable show-password/></el-form-item>-->
        <el-form-item label="更新密码" v-if="pkid">
          <el-input
            v-model="addUser.loginpassword"
            show-password
            clearable
          />
        </el-form-item>
        <el-form-item
          label="确认密码"
          prop="checkpassword"
          v-if="!pkid"
        >
          <el-input
            v-model="addUser.checkpassword"
            clearable
            show-password
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="userphone">
          <el-input
            v-model="addUser.userphone"
            @change="onPhoneChange"
            clearable
          />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="useremail">
          <el-input v-model="addUser.useremail" clearable />
        </el-form-item>
        <el-form-item label="用户角色" prop="roleId">
          <el-select
            placeholder="请选择"
            v-model="addUser.roleId"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.pkid"
              :label="item.roleName"
              :value="item.pkid"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-cascader
            v-model="addUser.deptId"
            :options="departmentTreeData"
            :props="{
              value: 'pkid',
              label: 'deptName',
              children: 'childTree',
              checkStrictly: true,
              disabled: 'deptStatus'
            }"
          />
        </el-form-item>
        <!-- <el-form-item label="用户等级" prop="userLevel">
          <el-radio v-model="addUser.userLevel" :label="1"
            >普通用户</el-radio
          >
          <el-radio v-model="addUser.userLevel" :label="3"
            >超级管理员</el-radio
          >
        </el-form-item> -->
        <el-form-item label="用户状态" prop="userstate">
          <!-- <el-switch
            v-model='forbidden'
            active-text='禁用'>
          </el-switch> -->
          <el-switch v-model="start" active-text="启用">
          </el-switch>
        </el-form-item>
        <el-form-item label="批交办用户" prop="issueFlag">
          <el-switch
            v-model="addUser.issueFlag"
            active-text="是"
            inactive-text="否"
            active-value="是"
            inactive-value="否"
          />
        </el-form-item>
        <el-form-item label="备注名">
          <el-input v-model="addUser.remark" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="onClose">取消</el-button>
        <el-button
          type="primary"
          @click="onSubmit('ruleForm')"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Base64 } from 'js-base64'
import {
  userQuery,
  userAdd,
  userUpdate,
  userDelete
} from '@/api/user'
import { getDeptTree } from '@/api/dept'
import { roleQuery } from '@/api/role'
import Icon from '@/components/icon'

export default {
  name: 'index',
  components: {
    Icon
  },
  data() {
    const Reg = (str, rStr) => {
      let reg = new RegExp(rStr)
      if (reg.test(str)) return true
      else return false
    }
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback()
      } else {
        let rC = {
          lW: '[a-z]', // 小写字母
          uW: '[A-Z]', // 大写字母
          nW: '[0-9]', // 汉字
          sW: '[\\u0020-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]' // 特殊字符
        }
        if (str.length < 8) {
          callback(new Error('请至少输入8位及以上密码'))
        } else {
          let tR = {
            l: Reg(str, rC.lW),
            u: Reg(str, rC.uW),
            n: Reg(str, rC.nW),
            s: Reg(str, rC.sW)
          }
          if (
            (tR.l && tR.u && tR.n) ||
            (tR.l && tR.u && tR.s) ||
            (tR.s && tR.u && tR.n) ||
            (tR.s && tR.l && tR.n)
          ) {
            // 密码符合要求
            callback()
          } else {
            callback(
              new Error(
                '密码必须含有“小写字母”、“大写字母”、“数字”、“特殊符号”中的任意三种'
              )
            )
          }
        }
      }
    }
    return {
      userList: [],
      total: '',
      headerTitle: '新增用户',
      pkid: '',
      parameter: {
        sortField: '',
        pageSize: 10,
        pageIndex: 1,
        sortType: '',
        userName: '',
        userState: '',
        deptId: '',
        roleId: ''
      },
      stateOptions: [
        // {
        //   label: '全部',
        //   value: ''
        // },
        {
          label: '启用',
          value: 1
        },
        {
          label: '禁用',
          value: 2
        }
      ],
      roleOptions: [],
      deptTree: [],
      addUser: {
        loginname: '',
        loginpassword: '',
        checkpassword: '',
        userName: '',
        useremail: '',
        userphone: '',
        userstate: 1,
        userLevel: 1,
        remark: '',
        cause: '',
        roleId: 'common',
        deptId: '',
        issueFlag: ''
      },
      updateOriginPhone: '',
      shouldPassPhoneParam: false,
      rules: {
        loginname: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ],
        loginpassword: [
          {
            required: true,
            message: '请输入登录密码',
            trigger: 'blur'
          },
          {
            min: 8,
            message: '密码至少8位',
            trigger: 'blur'
          },
          {
            pattern:
              /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]{8,30}$/,
            message:
              '至少包含大写字母、小写字母、数字和特殊符号(_)中其中三种',
            trigger: 'blur'
          }
        ],
        checkpassword: [
          {
            required: true,
            message: '请输入确认密码',
            trigger: 'blur'
          },
          {
            min: 8,
            message: '密码至少8位',
            trigger: 'blur'
          },
          {
            pattern:
              /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]{8,30}$/,
            message:
              '至少包含大写字母、小写字母、数字和特殊符号(_)中其中三种',
            trigger: 'blur'
          }
        ],
        oldloginpassword: [
          {
            required: true,
            message: '请输入更新密码',
            trigger: 'blur'
          },
          {
            min: 8,
            message: '密码至少8位',
            trigger: 'blur'
          },
          {
            pattern:
              /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{8,}$/,
            message:
              '至少包含大写字母、小写字母、数字和特殊符号(_)中其中三种',
            trigger: 'blur'
          }
        ],
        // userName: [
        //   {
        //     required: true,
        //     message: '请输入真实姓名',
        //     trigger: 'blur'
        //   }
        // ],
        useremail: [
          {
            required: false,
            message: '请输入电子邮箱',
            trigger: 'blur'
          }
        ],
        // userphone: [
        //   {
        //     required: true,
        //     message: '请输入联系电话',
        //     trigger: 'blur'
        //   }
        // ],
        userLevel: [
          {
            required: true,
            message: '请选择用户等级',
            trigger: 'change'
          }
        ],
        roleId: [
          {
            required: true,
            message: '请选择用户角色',
            trigger: 'change'
          }
        ],
        userstate: [
          {
            required: true,
            message: '请选择用户状态',
            trigger: 'change'
          }
        ],
        deptId: [
          {
            required: true,
            message: '请选择所属部门',
            trigger: 'change'
          }
        ]
      },
      forbidden: false,
      start: true,
      dialogVisible: false
    }
  },
  watch: {
    start(value) {
      if (value) {
        this.addUser.userstate = 1
      } else {
        this.addUser.userstate = 0
      }
    }
    // forbidden(value) {
    //   if (value) {
    //     this.start = false
    //     this.addUser.userstate = 0
    //   }
    // }
  },
  computed: {
    departmentTreeData() {
      if (this.deptTree.length === 1) {
        return this.deptTree[0].childTree
      } else {
        return []
      }
    }
  },
  mounted() {
    roleQuery({
      pageSize: 9999,
      pageIndex: 1
    }).then((res) => {
      if (res.success) {
        this.roleOptions = res.data.list
        // console.log(this.roleOptions, 'roleOptions')
      }
    })
    getDeptTree().then((res) => {
      if (res.success) {
        this.deptTree = this.deptScreen(res.data)
      } else {
        this.$message.error(res.message)
      }
    })
    this.getList()
  },
  methods: {
    search() {
      console.log(this.parameter, 'par')
      this.parameter.pageIndex = 1
      this.total = ''
      if (Array.isArray(this.parameter.deptId)) {
        this.parameter.deptId =
          this.parameter.deptId[
            this.parameter.deptId.length - 1
          ]
      }
      this.getList()
    },
    // pageChange
    pageChange(page) {
      this.parameter.pageIndex = page
      this.getList()
    },
    // 获取用户列表
    getList() {
      userQuery(this.parameter).then((res) => {
        if (res.success) {
          this.userList = res.data.list
          this.total = res.data.count
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 编辑删除
    updateUser(item) {
      this.addUser.deptId = item.deptId
      this.addUser.roleId = item.roleId
      this.addUser.userLevel = item.userLevel
      this.addUser.remark = item.remark
      this.addUser.userName = item.userName
      this.addUser.loginname = item.loginName
      this.addUser.useremail = item.userEmail
      this.addUser.userphone = item.userPhone
      this.addUser.issueFlag = item.issueFlag
      this.updateOriginPhone = item.userPhone
      this.start = item.userState === 1
      this.pkid = item.pkid
      this.dialogVisible = true
      this.headerTitle = '编辑用户'
      this.shouldPassPhoneParam = false
    },
    deleteUser(item) {
      this.$confirm(
        '此操作将永久删除该用户，是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          userDelete(item.pkid).then((res) => {
            if (res.success) {
              this.$message.success(res.data)
              if (
                this.total % 10 === 1 &&
                this.parameter.pageIndex ===
                  parseInt(this.total / 10) + 1 &&
                this.parameter.pageIndex !== 1
              ) {
                this.parameter.pageIndex -= 1
              }
              this.onClose()
            } else {
              this.$message.error(res.message)
            }
          })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // tanble row
    tableRowClassName({ rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'light'
      } else {
        return ''
      }
    },
    // 部门树筛选
    deptScreen(data) {
      data.map((item) => {
        item.deptStatus = item.deptStatus === 0
        if (item.childTree.length < 1) {
          item.childTree = undefined
        } else {
          this.deptScreen(item.childTree)
        }
      })
      return data
    },
    // 取消
    onClose() {
      this.addUser.deptId = ''
      this.addUser.userstate = 1
      this.start = true
      this.addUser.loginname = ''
      this.addUser.cause = ''
      this.addUser.remark = ''
      this.addUser.loginpassword = ''
      this.addUser.checkpassword = ''
      this.addUser.useremail = ''
      this.addUser.userLevel = 1
      this.addUser.userName = ''
      this.addUser.userphone = ''
      this.addUser.roleId = 'common'
      this.addUser.issueFlag = ''
      this.dialogVisible = false
      this.pkid = ''
      this.getList()
    },
    // 添加
    onSubmit(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          if (this.pkid) {
            // 编辑
            // this.addUser.oldloginpassword = Base64.encode(this.addUser.oldloginpassword)
            if (this.addUser.loginpassword) {
              this.addUser.loginpassword = Base64.encode(
                this.addUser.loginpassword
              )
            } else {
              delete this.addUser.loginpassword
            }
            if (Array.isArray(this.addUser.deptId)) {
              this.addUser.deptId =
                this.addUser.deptId[
                  this.addUser.deptId.length - 1
                ]
            }
            const params = { ...this.addUser }
            if (!this.shouldPassPhoneParam) {
              delete params.userphone
            }
            userUpdate(params, this.pkid).then((res) => {
              if (res.success) {
                this.$message.success(res.data)
                this.onClose()
              } else {
                this.addUser.loginpassword = ''
                this.addUser.oldloginpassword = ''
                this.$message.error(res.message)
              }
            })
          } else {
            if (
              this.addUser.checkpassword !==
              this.addUser.loginpassword
            ) {
              this.$message.error('登录密码与确认密码不同')
              this.addUser.loginpassword = ''
              this.addUser.checkpassword = ''
              return
            }
            // 新增
            if (Array.isArray(this.addUser.deptId)) {
              this.addUser.deptId =
                this.addUser.deptId[
                  this.addUser.deptId.length - 1
                ]
            }
            this.addUser.loginpassword = Base64.encode(
              this.addUser.loginpassword
            )
            userAdd(this.addUser).then((res) => {
              if (res.success) {
                this.$message.success(res.data)
                this.onClose()
              } else {
                this.addUser.loginpassword = Base64.decode(
                  this.addUser.loginpassword
                )
                this.$message.error(res.message)
              }
            })
          }
        }
      })
    },
    onPhoneChange(val) {
      console.log('onPhoneChange', val)
      if (this.pkid) {
        // 编辑
        this.shouldPassPhoneParam =
          this.updateOriginPhone !== val
        console.log(
          '是否传手机号',
          this.shouldPassPhoneParam
        )
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import '~@/assets/css/table.scss';
::v-deep .el-dialog {
  .el-dialog__header {
    background: #597182 !important;
    padding: 8px 0 14px 24px !important;
    height: 39px !important;

    .el-dialog__title {
      font-size: 16px !important;
      line-height: 22px;
      font-weight: 400 !important;
      color: white !important;
      //margin:19px 0 14px 24px !important;
    }

    .el-dialog__headerbtn {
      font-size: 16px;
      top: 10px !important;
      right: 17px !important;
      color: white !important;

      .el-dialog__close {
        color: white !important;
      }
    }
  }

  .el-dialog__body {
    padding: 17px 32px 18px 26px !important;

    .el-form-item {
      margin-bottom: 19px !important;
    }
  }

  .el-input__inner {
    height: 34px !important;
    background-color: #f6f9fc !important;
  }

  .el-button--default {
    border-color: #497fa3 !important;

    span {
      color: #497fa3 !important;
    }
  }

  .el-button--primary {
    background: #497fa3 !important;
    border-color: white !important;
  }
}
</style>
